const express = require("express");
const router = express.Router();
const { getFileName, checkFile } = require("../models/files.js");
const multer = require("multer");
const path = require("path");
const fs = require("fs")


let obj = multer({ dest: "./upload" })


router.get("/", (req, res) => {
    getFileName((files) => {
        res.render("index", { files })
    })
})

router.get("/up", (req, res) => {
    getFileName((files) => {
        res.render("up", { files })
    })
})

router.post("/ablum", obj.single("tupian"), (req, res) => {
    if (!req.file) {
        res.send("请选择正确的上传的图片")
    }

    let filename = req.file.filename;
    let extname = path.extname(req.file.originalname);
    let filedir = req.body.folder;

    fs.rename(`./upload/${filename}`, `./upload/${filedir}/${filename}${extname}`, (err, data) => {
        if (err) {
            return err;
        }

        getFileName((files) => {
            res.render("up", { files })
        })
    })
})



router.get("/:folder", (req, res) => {
    checkFile(req.params.folder, (files) => {
        res.render("ablum", {
            albumname: req.params.folder,
            picsFiles: files
        })
    })
})


module.exports = router;